package com.bub.pay.mq.consumer.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @ClassName: HttpHelper
 * @Description:
 * @author Leo
 */
public class HttpHelper {

	private static final Logger log = LoggerFactory.getLogger(HttpHelper.class);

	private static CloseableHttpAsyncClient httpClient;

	static {

		IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
				.setIoThreadCount(Runtime.getRuntime().availableProcessors()).setSoKeepAlive(true).build();
		// 设置连接池大小
		ConnectingIOReactor ioReactor = null;
		try {
			ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
		} catch (IOReactorException e) {
			e.printStackTrace();
		}
		PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
		cm.setMaxTotal(500);
		cm.setDefaultMaxPerRoute(100);

		RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
		// 客户端和服务器建立连接的timeout
		requestConfigBuilder.setConnectTimeout(30000);
		// 从连接池获取连接的timeout
		requestConfigBuilder.setConnectionRequestTimeout(30000);
		// 连接建立后，request没有回应的timeout
		requestConfigBuilder.setSocketTimeout(30000);
		HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();
		clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
		// 连接建立后，request没有回应的timeout
		clientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
		clientBuilder.setConnectionManager(cm);
		httpClient = clientBuilder.build();
		httpClient.start();
	}

	public static String getMethod(String url) {
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response;
		try {
			final Future<HttpResponse> future = httpClient.execute(httpGet, null);
			response = future.get();
			return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
		} catch (Exception ex) {
			log.error("http error:", ex);
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	public static String postMethod(String url, Map<String, Object> param) throws IOException {
		log.info("HTTP请求URL:" + url);
		log.info("HTTP请求参数:" + JSON.toJSONString(param));
		HttpPost httpost = new HttpPost(url);
		HttpResponse response;
		try {
			StringEntity entity = new StringEntity(JSON.toJSONString(param), ContentType.APPLICATION_JSON);
			httpost.setEntity(entity);
			final Future<HttpResponse> future = httpClient.execute(httpost, null);
			response = (HttpResponse) future.get();
			return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
		} catch (Exception ex) {
			log.error("http error:", ex);
		} finally {
			httpost.releaseConnection();
		}
		return null;
	}

//	public static void main(String[] args) {
//		SortedMap<String,Object> dataMap = new TreeMap<>();
//		dataMap.put("orderNo","201907291541311001652");
//		dataMap.put("merOrderNo","10000014");
//
//		dataMap.put("orderState",1);
//		dataMap.put("amount",new BigDecimal("100"));
//
//		StringBuilder sb = new StringBuilder();
//		dataMap.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
//		sb.append("key=7ba4dc09fc62038450934c1650bdf8b5");
//
//		System.out.println(sb);
//		System.out.println(DigestUtils.md5Hex(sb.toString()).toUpperCase());
//	}

}
